<template>
  <div class="supplier-edit">
    <el-card class="box-card">
      <div slot="header">
        <span>{{ isEdit ? '编辑供应商' : '新增供应商' }}</span>
      </div>
      
      <el-form 
        ref="form" 
        :model="form" 
        :rules="rules"
        label-width="120px"
        size="small"
      >
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model.trim="form.supplierName" placeholder="请输入供应商名称" />
        </el-form-item>

        <el-form-item label="联系人" prop="contactName">
          <el-input v-model.trim="form.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>

        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model.trim="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="form.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input 
            v-model.trim="form.address" 
            type="textarea"
            :rows="3"
            placeholder="请输入地址"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input 
            v-model.trim="form.password" 
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submitForm">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getSupplierDetail, addSupplier, updateSupplier } from '@/api/suppliers'

export default {
  name: 'SupplierEdit',
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入联系电话'))
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    // 邮箱验证规则
    const validateEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入邮箱'))
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
        callback(new Error('请输入正确的邮箱地址'))
      } else {
        callback()
      }
    }

    return {
      loading: false,
      isEdit: false,
      form: {
        supplierId: undefined,
        supplierName: '',
        contactName: '',
        contactPhone: '',
        email: '',
        address: '',
        password: ''
      },
      rules: {
        supplierName: [
          { required: true, message: '请输入供应商名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        contactName: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        email: [
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' },
          { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    const { id } = this.$route.params
    if (id) {
      this.isEdit = true
      this.getDetail(id)
    }
  },
  methods: {
    // 获取详情
    async getDetail(id) {
      try {
        const res = await getSupplierDetail(id)
        if (res.code === 200 && res.data) {
          const { supplierId, supplierName, contactName, contactPhone, email, address } = res.data
          this.form = { supplierId, supplierName, contactName, contactPhone, email, address }
        }
      } catch (error) {
        this.$message.error('获取供应商信息失败')
        console.error(error)
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        
        this.loading = true
        try {
          // 构建提交数据，参考用户编辑的方式
          const submitData = {
            supplierName: this.form.supplierName,
            contactName: this.form.contactName,
            contactPhone: this.form.contactPhone,
            email: this.form.email,
            address: this.form.address
          }

          // 如果是编辑模式，添加ID
          if (this.isEdit) {
            submitData.supplierId = this.form.supplierId
          } else {
            // 如果是新增模式，添加密码
            submitData.password = this.form.password
          }

          // 调用API
          const api = this.isEdit ? updateSupplier : addSupplier
          const res = await api(submitData)
          
          if (res.code === 200) {
            this.$message.success(`${this.isEdit ? '更新' : '新增'}成功`)
            this.cancel()
          } else {
            this.$message.error(res.msg || `${this.isEdit ? '更新' : '新增'}失败`)
          }
        } catch (error) {
          console.error(`${this.isEdit ? '更新' : '新增'}失败:`, error)
          this.$message.error(error.response?.data?.message || `${this.isEdit ? '更新' : '新增'}失败`)
        } finally {
          this.loading = false
        }
      })
    },
    // 取消
    cancel() {
      this.$router.push('/supplier/list')
    }
  }
}
</script>

<style lang="less" scoped>
.supplier-edit {
  padding: 20px;
  
  .el-card {
    max-width: 800px;
    margin: 0 auto;
  }
}
</style>